package control_plane

/**
 * @Description 新建控制面实例
 * @Author 007lz
 * @Date 2024/7/10 下午4:46
 **/
import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"strings"
	"time"

	"gitee.com/git-lz/twelve/common/consts"
	"gitee.com/git-lz/twelve/common/zaplog"
	"gitee.com/git-lz/twelve/logic/node"
	"gitee.com/git-lz/twelve/logic/task_manager/cache"
	"gitee.com/git-lz/twelve/model/task"
	"go.uber.org/zap"
)

// ControlPlane 控制面对象
// Request 上游请求参数
type ControlPlane struct {
	Task        *task.Task
	TaskContext *task.TaskContext
}

func NewDefault() *ControlPlane {
	return &ControlPlane{}
}

func New() *ControlPlane {
	return &ControlPlane{}
}

// 获取需要的任务配置
func (c *ControlPlane) setTask(ctx context.Context, request *http.Request, path string) error {
	start := time.Now()

	taskMap := cache.GetGlobalTaskMemCache()
	if taskMap == nil {
		zaplog.Errorf(ctx, consts.DLTagTaskNotFind, start)
		return errors.New("no tasks")
	}

	triggerPath := fmt.Sprintf("%s_%s", strings.TrimLeft(path, "/"), strings.ToLower(request.Method))
	version2Tasks, ok := taskMap[triggerPath]
	if !ok {
		zaplog.Errorf(ctx, consts.DLTagTaskNotFind, start, zap.String("triggerPath", triggerPath))
		return errors.New(fmt.Sprintf("task not found, triggerPath=%s", triggerPath))
	}

	return c.filterByVersion(ctx, version2Tasks)
}

func (c *ControlPlane) getTaskContext(ctx context.Context, request *http.Request, path string) error {
	taskContext := &task.TaskContext{}
	nodeMap := make(map[string]node.INode)

	task := c.Task
	for nodeId, nodeInfo := range task.Nodes {
		nodeInstance, err := node.NewINode(nodeInfo.Key)
		if err != nil {
			return err
		}

		nodeMap[nodeId] = nodeInstance
	}

	taskContext.NodeMap = nodeMap
	taskContext.Path = path
	taskContext.Request = request
	c.TaskContext = taskContext
	return nil
}
